package com.chao.wind3j.base.config.shiroConfig;

import com.chao.wind3j.model.base.JwtToken;
import com.chao.wind3j.service.Wind3UserService;
import lombok.SneakyThrows;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class JwtRealm extends AuthorizingRealm {

  @Autowired
  private Wind3UserService wind3UserService;

  public JwtRealm(Wind3UserService wind3UserService) {
    this.wind3UserService = wind3UserService;
  }

  @Override
  public boolean supports(AuthenticationToken token) {
    return token instanceof JwtToken;
  }
  @SneakyThrows
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    var jwtToken = (JwtToken) principalCollection.getPrimaryPrincipal();
    var subject = SecurityUtils.getSubject();
//    var apiUser = this.cacheRedisUserService.getUserInfoByToken(jwtToken.getToken());
    var simpleAuthorizationInfo = new SimpleAuthorizationInfo();
    simpleAuthorizationInfo.addRole("admin");
    simpleAuthorizationInfo.addStringPermission("user:main");
    System.out.println("authc + " + simpleAuthorizationInfo);
    return simpleAuthorizationInfo;
  }

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
    var jwtToken = (JwtToken) authenticationToken;
    return new SimpleAuthenticationInfo(jwtToken, jwtToken.getToken(), getName());
  }
}
